package com.apexedu.biz.controller;

import com.alibaba.fastjson.JSON;
import com.apexedu.biz.UrlsConst;
import com.apexedu.biz.entity.client.*;
import com.apexedu.biz.service.impl.AuthServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 访问鉴权控制器
 *
 * @author Yangjianliang
 *         datetime 2013-11-12
 */
@Controller
public class AuthController {

    private static final Log LOG = LogFactory.getLog(AuthController.class);

    @Resource(name = "authServiceImpl")
    AuthServiceImpl authService;

    /**
     * 获取指定用户的所有资源
     *
     * @param userLoginId
     * @return
     */
    @RequestMapping(value = UrlsConst.GET_SRC_USERLOGINID, method = RequestMethod.GET)
    public
    @ResponseBody
    String getResourcesByAssignUser(@PathVariable String userLoginId, HttpServletRequest request) {
        CommandResult result;
        String clientAppId = request.getHeader("AuC"); // 客户端接入号
        try {
            result = authService.getResourcesByAssignUser(clientAppId, userLoginId);
        } catch (Exception e) {
            LOG.error(e);
            result = new CommandResult();
            result.setHasError(true);
            result.setError(e.getMessage());
        }
        return JSON.toJSONString(result); // 客户端也使用 fastJson 转换
    }

    /**
     * 获取添加到门户的所有资源
     */
    @RequestMapping(value = UrlsConst.DOWNLOAD_RESOURCE_PORTAL, method = RequestMethod.GET)
    public
    @ResponseBody
    String getPortalResource(HttpServletRequest request) {
        CommandResult result;
        String clientAppId = request.getHeader("AuC");//客户端接入号
        try {
            result = authService.getPortalResources(clientAppId);
        } catch (Exception e) {
            LOG.error(e);
            result = new CommandResult();
            result.setHasError(true);
            result.setError(e.getMessage());
        }
        return JSON.toJSONString(result);
    }

    /**
     * 验证指定用户的资源权限
     *
     * @param userLoginId
     * @return
     */
    @RequestMapping(value = UrlsConst.AUTH_USERLOGINID_SRCID, method = RequestMethod.GET)
    public
    @ResponseBody
    String checkRights(@PathVariable String userLoginId,
                       @PathVariable String srcId, HttpServletRequest request) {
        CommandResult result;
        String clientAppId = request.getHeader("AuC"); // 客户端接入号
        try {
            result = authService.checkRights(clientAppId, userLoginId, srcId);
        } catch (Exception e) {
            LOG.error(e);
            result = new CommandResult();
            result.setHasError(true); // 默认是false
            result.setError(e.getMessage());
        }
        return JSON.toJSONString(result); // 客户端也使用 fastJson 转换
    }

    /**
     * 上传本地资源到服务器
     *
     * @return
     */
    @RequestMapping(value = UrlsConst.UPLOAD_RESOURCES, method = RequestMethod.POST)
    public
    @ResponseBody
    String uploadResources(HttpServletRequest request) {
        return execUploadRequest(request, 1);
    }

    /**
     * 删除服务端资源
     *
     * @return
     */
    @RequestMapping(value = UrlsConst.DELETE_RESOURCES, method = RequestMethod.POST)
    public
    @ResponseBody
    String deleteResources(HttpServletRequest request) {
        return execDeleteRequest(request, 1);
    }

    /**
     * 角色
     */
    @RequestMapping(value = UrlsConst.UPLOAD_ROLES, method = RequestMethod.POST)
    public
    @ResponseBody
    String uploadRoles(HttpServletRequest request) {
        return execUploadRequest(request, 2);
    }

    @RequestMapping(value = UrlsConst.DELETE_ROLES, method = RequestMethod.POST)
    public
    @ResponseBody
    String deleteRoles(HttpServletRequest request) {
        return execDeleteRequest(request, 2);
    }

    /**
     * 角色、资源关系
     */
    @RequestMapping(value = UrlsConst.UPLOAD_ROLE_RESOURCE_MAP, method = RequestMethod.POST)
    public
    @ResponseBody
    String uploadRoleResourceMap(HttpServletRequest request) {
        return execUploadRequest(request, 3);
    }

    @RequestMapping(value = UrlsConst.DELETE_ROLE_RESOURCE_MAP, method = RequestMethod.POST)
    public
    @ResponseBody
    String deleteRoleResourceMap(HttpServletRequest request) {
        return execDeleteRequest(request, 3);
    }

    /**
     * 角色、用户关系
     */
    @RequestMapping(value = UrlsConst.UPLOAD_ROLE_USER_MAP, method = RequestMethod.POST)
    public
    @ResponseBody
    String uploadRoleUserMap(HttpServletRequest request) {
        return execUploadRequest(request, 4);
    }

    @RequestMapping(value = UrlsConst.DELETE_ROLE_USER_MAP, method = RequestMethod.POST)
    public
    @ResponseBody
    String deleteRoleUserMap(HttpServletRequest request) {
        return execDeleteRequest(request, 4);
    }

    /**
     * 用户管理
     */
    @RequestMapping(value = UrlsConst.UPLOAD_USER, method = RequestMethod.POST)
    public
    @ResponseBody
    String uploadUser(HttpServletRequest request) {
        return execUploadRequest(request, 5);
    }

    @RequestMapping(value = UrlsConst.DELETE_USER, method = RequestMethod.POST)
    public
    @ResponseBody
    String deleteUser(HttpServletRequest request) {
        return execDeleteRequest(request, 5);
    }

    @RequestMapping(value = UrlsConst.UPDATE_OR_DELETE_RESOURCE, method = RequestMethod.POST)
    public
    @ResponseBody
    String updateOrDeleteResource(HttpServletRequest request) {
        return updateOrDeleteRequest(request, 1);
    }

    @RequestMapping(value = UrlsConst.UPDATE_OR_DELETE_ROLEANDRESOURCEMAP, method = RequestMethod.POST)
    public
    @ResponseBody
    String updateOrDeleteRoleResource(HttpServletRequest request) {
        return updateOrDeleteRequest(request, 2);
    }

    @RequestMapping(value = UrlsConst.UPDATE_OR_DELETE_ROLE, method = RequestMethod.POST)
    public
    @ResponseBody
    String updateOrDeleteRole(HttpServletRequest request) {
        return updateOrDeleteRequest(request, 3);
    }

    /**
     * 处理客户端提交的post请求
     *
     * @param request
     * @param targetMethod
     * @return
     */
    private String execUploadRequest(HttpServletRequest request, int targetMethod) {
        CommandResult result;
        String clientAppId = request.getHeader("AuC"); // 客户端接入号
        String resources = request.getParameter("dataList"); // 客户端都把List对象转为json，用这个参数提交上来
        if (StringUtils.isNotBlank(clientAppId) && StringUtils.isNotBlank(resources)) {
            try {
                switch (targetMethod) {
                    case 1:
                        List<ResourceEntity> resourceEntities = JSON.parseArray(resources, ResourceEntity.class);
                        result = authService.uploadResourcesBySTA(resourceEntities, clientAppId);
                        break;
                    case 2:
                        List<RoleEntity> dataList = JSON.parseArray(resources, RoleEntity.class);
                        result = authService.uploadRolesBySTA(dataList, clientAppId);
                        break;
                    case 3:
                        List<RoleResourceMapEntity> roleResourceMapEntities = JSON.parseArray(resources, RoleResourceMapEntity.class);
                        result = authService.uploadRoleResourceMapBySTA(roleResourceMapEntities, clientAppId);
                        break;
                    case 4:
                        List<RoleUserMapEntity> roleUserMapEntities = JSON.parseArray(resources, RoleUserMapEntity.class);
                        result = authService.uploadRoleUserMapBySTA(roleUserMapEntities, clientAppId);
                        break;
                    case 5:
                        List<UserEntity> roleUserEntities = JSON.parseArray(resources, UserEntity.class);
                        result = authService.uploadUserBySTA(roleUserEntities, clientAppId);
                        break;
                    default:
                        result = new CommandResult();
                        result.setHasError(true); // 默认是false
                        result.setError("请求方法不正确！");
                        break;
                }
            } catch (Exception e) {
                LOG.error(e);
                result = new CommandResult();
                result.setHasError(true); // 默认是false
                result.setError(e.getMessage());
            }
        } else {
            result = new CommandResult();
            result.setHasError(true); // 默认是false
            result.setError("请提交资源数据！");
        }
        return JSON.toJSONString(result); // 客户端也使用 fastJson 转换
    }

    private String execDeleteRequest(HttpServletRequest request, int targetMethod) {
        CommandResult result;
        String clientAppId = request.getHeader("AuC"); // 客户端接入号
        String resources = request.getParameter("dataList"); // 客户端都把List对象转为json，用这个参数提交上来
        if (StringUtils.isNotBlank(clientAppId) && StringUtils.isNotBlank(resources)) {
            try {
                switch (targetMethod) {
                    case 1:
                        List<ResourceEntity> resourceEntities = JSON.parseArray(resources, ResourceEntity.class);
                        result = authService.deleteResourcesBySTA(resourceEntities, clientAppId);
                        break;
                    case 2:
                        List<RoleEntity> dataList = JSON.parseArray(resources, RoleEntity.class);
                        result = authService.deleteRolesBySTA(dataList, clientAppId);
                        break;
                    case 3:
                        List<RoleResourceMapEntity> roleResourceMapEntities = JSON.parseArray(resources, RoleResourceMapEntity.class);
                        result = authService.deleteRoleResourceMapBySTA(roleResourceMapEntities, clientAppId);
                        break;
                    case 4:
                        List<RoleUserMapEntity> roleUserMapEntities = JSON.parseArray(resources, RoleUserMapEntity.class);
                        result = authService.deleteRoleUserMapBySTA(roleUserMapEntities, clientAppId);
                        break;
                    case 5:
                        List<UserEntity> roleUserEntities = JSON.parseArray(resources, UserEntity.class);
                        result = authService.deleteUserBySTA(roleUserEntities, clientAppId);
                        break;
                    default:
                        result = new CommandResult();
                        result.setHasError(true); // 默认是false
                        result.setError("请求方法不正确！");
                        break;
                }
            } catch (Exception e) {
                LOG.error(e);
                result = new CommandResult();
                result.setHasError(true); // 默认是false
                result.setError(e.getMessage());
            }
        } else {
            result = new CommandResult();
            result.setHasError(true); // 默认是false
            result.setError("请提交资源数据！");
        }
        return JSON.toJSONString(result); // 客户端也使用 fastJson 转换
    }

    @RequestMapping(value = UrlsConst.GET_ACCESS_SYSTEMS, method = RequestMethod.GET)
    public
    @ResponseBody
    String getAccessSystems(HttpServletRequest request) {
        String clientAppId = request.getHeader("AuC"); // 客户端接入号
        CommandResult result;
        try {
            result = authService.getAccessSystems(clientAppId);
        } catch (Exception e) {
            LOG.error(e);
            result = new CommandResult();
            result.setHasError(true); // 默认是false
            result.setError(e.getMessage());
        }
        return JSON.toJSONString(result); // 客户端也使用 fastJson 转换
    }

    /**
     * 获取指定资源所关联的所有角色
     *
     * @param resourceid
     * @return
     */
    @RequestMapping(value = UrlsConst.GET_ROLE_RESOURCE, method = RequestMethod.GET)
    public
    @ResponseBody
    String getRoleByResource(@PathVariable String resourceid, HttpServletRequest request) {
        CommandResult result;
        String clientAppId = request.getHeader("AuC"); // 客户端接入号
        try {
            result = authService.getRoleByResource(clientAppId, resourceid);
        } catch (Exception e) {
            LOG.error(e);
            result = new CommandResult();
            result.setHasError(true);
            result.setError(e.getMessage());
        }
        return JSON.toJSONString(result); // 客户端也使用 fastJson 转换
    }

    public String updateOrDeleteRequest(HttpServletRequest request, int targetMethod) {
        CommandResult result;
        String id = request.getHeader("AuC"); // 客户端接入号
        String resources = request.getParameter("dataList"); // 客户端都把List对象转为json，用这个参数提交上来
        if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(resources)) {
            try {
                switch (targetMethod) {
                    case 1:
                        List<ResourceEntity> resourceEntities = JSON.parseArray(resources, ResourceEntity.class);
                        result = authService.updateOrDeleteResource(resourceEntities, id);
                        break;
                    case 2:
                        List<RoleResourceMapEntity> roleResourceMapEntities = JSON.parseArray(resources, RoleResourceMapEntity.class);
                        result = authService.updateOrDeleteResourceRoleMap(roleResourceMapEntities, id);
                        break;
                    case 3:
                        List<RoleEntity> roleEntities = JSON.parseArray(resources, RoleEntity.class);
                        result = authService.updateOrDeleteRole(roleEntities, id);
                        break;
                    default:
                        result = new CommandResult();
                        result.setHasError(true); // 默认是false
                        result.setError("请求方法不正确！");
                        break;
                }
            } catch (Exception e) {
                LOG.error(e);
                result = new CommandResult();
                result.setHasError(true); // 默认是false
                result.setError(e.getMessage());
            }
        } else {
            result = new CommandResult();
            result.setHasError(true); // 默认是false
            result.setError("请提交资源数据！");
        }
        return JSON.toJSONString(request);
    }

}
